package iot

import (
	"gorm.io/gorm"
	"iot-base/common/dbobj"
)

type (
	// ThingStation 场站关系.
	ThingStation dbobj.ThingStation

	ThingStationModel struct {
		db *gorm.DB
	}
)

func NewThingStationModel(db *gorm.DB) *ThingStationModel {
	return &ThingStationModel{
		db: db,
	}
}

// FindStationId 站点ID.
func (m *ThingStationModel) FindStationId(thingId string) (ThingStation, error) {
	var thingStation ThingStation
	err := m.db.Model(&ThingStation{}).Where("thing_id = ?", thingId).First(&thingStation).Error
	return thingStation, err
}

// WhereMapStation 根据map条件来查询数据.
func (m *ThingStationModel) WhereMapStation(params map[string]string) (ThingStation, error) {
	var thingStation ThingStation
	err := m.db.Model(&ThingStation{}).Where(params).First(&thingStation).Error
	return thingStation, err
}

func (t *ThingStationModel) DeleteMap(param map[string]interface{}) error {
	return t.db.Where(param).Delete(&ThingStation{}).Error
}

func (t *ThingStationModel) CountStationThings(stationId string) (int64, error) {
	var total int64
	err := t.db.Model(&ThingStation{}).Where("station_id = ?", stationId).Count(&total).Error
	return total, err
}
